package io.wdb.modules.generator.generator.service.impl.client;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;

import io.wdb.common.utils.HttpClientUtil;
import io.wdb.common.utils.PageHelperUtil;
import io.wdb.common.utils.Query;
import io.wdb.common.utils.SmsCodeUtil;
import io.wdb.modules.generator.generator.dao.AccountCreditDao;
import io.wdb.modules.generator.generator.dao.AccountCreditLogDao;
import io.wdb.modules.generator.generator.dao.BookCancelDao;
import io.wdb.modules.generator.generator.dao.BookEntityDao;
import io.wdb.modules.generator.generator.dao.BookMaintainLogDao;
import io.wdb.modules.generator.generator.dao.OrderTransDao;
import io.wdb.modules.generator.generator.dao.SmsVerificationLogDao;
import io.wdb.modules.generator.generator.dao.UserInfoDao;
import io.wdb.modules.generator.generator.dao.UserPointDao;
import io.wdb.modules.generator.generator.dao.UserPointLogDao;
import io.wdb.modules.generator.generator.entity.AccountCreditEntity;
import io.wdb.modules.generator.generator.entity.AccountCreditLogEntity;
import io.wdb.modules.generator.generator.entity.BookCancelEntity;
import io.wdb.modules.generator.generator.entity.BookEntityEntity;
import io.wdb.modules.generator.generator.entity.OrderTransEntity;
import io.wdb.modules.generator.generator.entity.SmsVerificationLogEntity;
import io.wdb.modules.generator.generator.entity.UserInfoEntity;
import io.wdb.modules.generator.generator.entity.UserPointEntity;
import io.wdb.modules.generator.generator.entity.UserPointLogEntity;
import io.wdb.modules.generator.generator.entity.customer.AccountCreditLogEntityCustomer;
import io.wdb.modules.generator.generator.entity.customer.BookEntityCustomer;
import io.wdb.modules.generator.generator.entity.customer.BookMaintainLogEntityCustomer;
import io.wdb.modules.generator.generator.entity.customer.OrderTransEntityCustomer;
import io.wdb.modules.generator.generator.entity.customer.UserInfoEntityCustomer;
import io.wdb.modules.generator.generator.entity.customer.UserPointLogEntityCustomer;
import io.wdb.modules.generator.generator.entity.web.ResponseEnum;
import io.wdb.modules.generator.generator.entity.web.WebResponse;
import io.wdb.modules.generator.generator.service.client.ClientManagerService;

@Service
public class ClientManagerServiceImpl implements ClientManagerService{

	private Logger logger = LoggerFactory.getLogger(ClientManagerServiceImpl.class);
	
	@Value("${wdb007.loginurl}")
	private String loginUrl;
	
	@Autowired
	private UserInfoDao userInfoDao;
	
	@Autowired
	private UserPointDao userPointDao;
	
	@Autowired
	private UserPointLogDao userPointLogDao;
	
	@Autowired
	private AccountCreditDao accountCreditDao;
	
	@Autowired
	private AccountCreditLogDao accountCreditLogDao;
	
	@Autowired
	private BookMaintainLogDao bookMaintainLogDao;
	
	@Autowired
	private SmsVerificationLogDao smsVerificationLogDao;
	
	@Autowired
	private OrderTransDao orderTransDao;
	
	@Autowired
	private BookEntityDao bookEntityDao;
	
	@Autowired
	private BookCancelDao bookCancelDao;
	@Override
	public List<UserInfoEntityCustomer> queryList(Query query) {
		//PageHelper.startPage(PageHelperUtil.getPageNum(query),PageHelperUtil.getPageSize(query));
		List<UserInfoEntityCustomer> customers = userInfoDao.queryListCustomer(query);
		for(UserInfoEntityCustomer customer:customers) {
			//查询每个用户的报修次数
			query.put("id", customer.getId());
			int maintainCount = bookMaintainLogDao.queryMainTainListTotal(query);
			customer.setRepairsNum(maintainCount);
			/*if(customer.getCashStatus()==1) {//已退押金查看是否存在退押金的记录
				UserChargeLogEntity chargeLogEntity = userChargeLogDao.getUserRefundLog(customer.getId());
				if(chargeLogEntity==null) {
					customer.setCashStatus(4);
				}
			}*/
		}
		return customers;
	}

	@Override
	public void updatePointValue(UserInfoEntityCustomer userInfoEntityCustomer) {
		//拉取用户原始积分
		UserPointEntity userPointEntityDb = userPointDao.queryByUserId(userInfoEntityCustomer.getId());
		Integer finalPointValue = userPointEntityDb.getPointValue()+userInfoEntityCustomer.getPointValue();
		userPointEntityDb.setPointValue(finalPointValue);
		userPointEntityDb.setModifyTime(new Date());
		userPointDao.updateByUserId(userPointEntityDb);
		//记录流水
		UserPointLogEntity userPointLogEntity = new UserPointLogEntity();
		if(userInfoEntityCustomer.getPointValue()<0) {
			userPointLogEntity.setChangeType(20);
		}else {
			userPointLogEntity.setChangeType(10);
		}
		userPointLogEntity.setDescription(userInfoEntityCustomer.getDescription());
		userPointLogEntity.setChangeValue(userInfoEntityCustomer.getPointValue());
		userPointLogEntity.setCreateTime(new Date());
		userPointLogEntity.setPointId(userPointEntityDb.getId());
		userPointLogDao.save(userPointLogEntity);
	}

	@Override
	public void updateCreditValue(UserInfoEntityCustomer userInfoEntityCustomer) {
		//拉取用户原始信用分
		AccountCreditEntity accountCreditEntityDB = accountCreditDao.queryByUserId(userInfoEntityCustomer.getId());
		accountCreditEntityDB.setModifyTime(new Date());
		Integer finalCreditValue = accountCreditEntityDB.getCreditValue()+userInfoEntityCustomer.getCreditValue();
		accountCreditEntityDB.setCreditValue(finalCreditValue);
		accountCreditDao.update(accountCreditEntityDB);
		//记录流水
		AccountCreditLogEntity accountCreditLogEntity = new AccountCreditLogEntity();
		accountCreditLogEntity.setCreateTime(new Date());
		accountCreditLogEntity.setAccountCreditId(accountCreditEntityDB.getId());
		if(userInfoEntityCustomer.getCreditValue()<0) {
			accountCreditLogEntity.setChangeType(20);
		}else {
			accountCreditLogEntity.setChangeType(10);
		}
		accountCreditLogEntity.setDescription(userInfoEntityCustomer.getDescription());
		accountCreditLogEntity.setChangeValue(userInfoEntityCustomer.getCreditValue());
		accountCreditLogDao.save(accountCreditLogEntity);
	}

	@Override
	public UserPointEntity getUserPoint(Long userId) {
		return userPointDao.queryByUserId(userId);
	}

	@Override
	public AccountCreditEntity getUserCredit(Long userId) {
		return accountCreditDao.queryByUserId(userId);
	}

	@Override
	public int updateUserInfo(UserInfoEntityCustomer userInfoEntityCustomer) {
		UserInfoEntity entity = userInfoDao.queryObject(userInfoEntityCustomer.getId());
		if(entity.getUserType()==userInfoEntityCustomer.getUserType()) {
			return 0;
		}
		return userInfoDao.update(userInfoEntityCustomer);
	}

	@Override
	public WebResponse insertUser(UserInfoEntityCustomer userInfoEntityCustomer) {
		WebResponse webResponse = new WebResponse();
		//首先校验添加的用户是否已经存在
		List<UserInfoEntityCustomer> entities =  userInfoDao.queryByMobileNo(userInfoEntityCustomer.getMobileNo());
		if(entities!=null&&entities.size()>0) {
			webResponse.setCode(ResponseEnum.USER_ADD_EXIST.getCode());
			webResponse.setMessage(ResponseEnum.USER_ADD_EXIST.getMessage());
			return webResponse;
		}
		//先模拟发送短信验证码，然后远程调用API登录接口
		SmsVerificationLogEntity smsVerificationLogEntity = new SmsVerificationLogEntity();
		smsVerificationLogEntity.setCreateTime(new Date());
		smsVerificationLogEntity.setMobileNo(userInfoEntityCustomer.getMobileNo());
		smsVerificationLogEntity.setStatus(0);
		smsVerificationLogEntity.setType(0);
		String code = SmsCodeUtil.getSmsCode();
		smsVerificationLogEntity.setVerificationCount(0);
		smsVerificationLogEntity.setVerificationCode(code);
		smsVerificationLogDao.save(smsVerificationLogEntity);
		//使用Http请求调用注册功能
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		BasicNameValuePair mobile_no = new BasicNameValuePair("mobile_no", userInfoEntityCustomer.getMobileNo());
		BasicNameValuePair verify_code = new BasicNameValuePair("verify_code", code);
		list.add(mobile_no);
		list.add(verify_code);
		try {
			String body = HttpClientUtil.getPostBodyDataNameValuePair(loginUrl+"/user/login", list);
			System.out.println(body);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
			webResponse.setCode(ResponseEnum.USER_ADD_FAIL.getCode());
			webResponse.setMessage(ResponseEnum.USER_ADD_FAIL.getMessage());
			return webResponse;
		}
		return null;
	}

	@Override
	public List<BookMaintainLogEntityCustomer> queryMainTainListByUserId(Query query) {
		//获取维修记录
		return bookMaintainLogDao.queryTainListByUserId(query);
	}

	@Override
	public int queryMainTainListTotal(Query query) {
		return bookMaintainLogDao.queryMainTainListTotal(query);
	}

	@Override
	public int queryListTotal(Query query) {
		return userInfoDao.queryListCustomerTotal(query);
	}

	@Override
	public List<OrderTransEntityCustomer> queryCurrentBorrowBooks(Query query) {
		PageHelper.startPage(PageHelperUtil.getPageNum(query),PageHelperUtil.getPageSize(query));
		return orderTransDao.queryCurrentBorrowBooks(query);
	}

	@Override
	public List<UserPointLogEntityCustomer> queryPointRecord(Query query) {
		PageHelper.startPage(PageHelperUtil.getPageNum(query),PageHelperUtil.getPageSize(query));
		List<UserPointLogEntityCustomer> entities = userPointLogDao.queryRecordList(query);
		for(UserPointLogEntityCustomer entity:entities) {
			if(entity.getChangeType()==20) {
				entity.setChangeValue(-entity.getChangeValue());
			}
			switch (entity.getChangeType()) {
			case 10:
				entity.setTypeContent("增加");
				break;
			case 20:
				entity.setTypeContent("减少");
				break;
			case 30:
				entity.setTypeContent("初始化赠送");
				break;
			case 40:
				entity.setTypeContent("系统赠送");
				break;
			case 41:
				entity.setTypeContent("登录");
				break;
			case 42:
				entity.setTypeContent("邀请下载");
				break;
			case 43:
				entity.setTypeContent("分享");
				break;
			case 44:
				entity.setTypeContent("首次完善用户资料");
				break;
			case 45:
				entity.setTypeContent("用户评论");
				break;
			case 46:
				entity.setTypeContent("用户点赞数");
				break;
			case 47:
				entity.setTypeContent("用户自助充值");
				break;
			case 48:
				entity.setTypeContent("完成一次借阅");
				break;
			case 49:
				entity.setTypeContent("首次缴纳押金");
				break;
			default:
				break;
			}
		}
		return entities;
	}

	@Override
	public List<AccountCreditLogEntityCustomer> queryCreditRecord(Query query) {
		PageHelper.startPage(PageHelperUtil.getPageNum(query),PageHelperUtil.getPageSize(query));
		List<AccountCreditLogEntityCustomer> entities = accountCreditLogDao.queryRecordList(query);
		for(AccountCreditLogEntityCustomer accountCreditLogEntity:entities) {
			if(accountCreditLogEntity.getChangeType()==20) {
				accountCreditLogEntity.setChangeValue(-accountCreditLogEntity.getChangeValue());
			}
			switch (accountCreditLogEntity.getChangeType()) {
			case 10:
				accountCreditLogEntity.setTypeContent("增加");
				break;
			case 20:
				accountCreditLogEntity.setTypeContent("减少");
				break;
			default:
				break;
			}
		}
		return entities;
	}

	@Override
	public WebResponse cancelBook(BookEntityCustomer bookEntity) {
		//三个数据，用户Id 书籍Rfid 流水Id
		WebResponse webResponse = new WebResponse();
		try {
			BookEntityEntity bookEntityEntityDb = bookEntityDao.queryObject(bookEntity.getRfidCode());
			if(bookEntityEntityDb==null) {
				webResponse.setCode(ResponseEnum.CANCEL_BOOK_NOT_EXIST.getCode());
				webResponse.setMessage(ResponseEnum.CANCEL_BOOK_NOT_EXIST.getMessage());
				return webResponse;
			}
			bookEntityEntityDb.setStatus(2);//用户损坏
			bookEntityEntityDb.setBorrowedStatus(1);//下架
			bookEntityDao.update(bookEntityEntityDb);
			OrderTransEntity orderTransEntityDb = orderTransDao.queryObject(bookEntity.getOrderTransId());
			if(orderTransEntityDb.getTransAmount()==null) {
				orderTransEntityDb.setTransAmount(new BigDecimal("0.00"));
			}
			orderTransEntityDb.setTransStatus(30);//完成
			orderTransEntityDb.setModifyTime(new Date());
			orderTransDao.update(orderTransEntityDb);
			//改两张表数据 book_entity order_trance
			//新增一张表：记录用户作废操作
			BookCancelEntity bookCancelEntity = new BookCancelEntity();
			bookCancelEntity.setCreateTime(new Date());
			bookCancelEntity.setDetail("");
			bookCancelEntity.setRfidCode(bookEntity.getRfidCode());
			bookCancelEntity.setUserId(bookEntity.getUserId());
			bookCancelDao.save(bookCancelEntity);
			webResponse.setCode(ResponseEnum.CANCEL_BOOK_SUCCESS.getCode());
			webResponse.setMessage(ResponseEnum.CANCEL_BOOK_SUCCESS.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			webResponse.setCode(ResponseEnum.CANCEL_BOOK_FAIL.getCode());
			webResponse.setMessage(ResponseEnum.CANCEL_BOOK_FAIL.getMessage());
		}
		return webResponse;
	}
}
